package com.gitee.funcy.multiple.datasource.config;

import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import com.gitee.funcy.multiple.datasource.datasource.MultiDataSourceTransactionFactory;
import com.gitee.funcy.multiple.datasource.util.ResourceUtil;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.ClassPathResource;

import javax.sql.DataSource;

/**
 * ｛这里添加描述｝
 *
 * @author funcy
 * @date 2019-09-24 18:57
 */
@Configuration
public class MybatisPlusConfig {

    private String mapperLocations = "classpath*:mapper/**/*.xml";

    @Bean("sqlSessionFactory")
    @DependsOn({"dynamicDataSource"})
    @Primary
    public MybatisSqlSessionFactoryBean sqlSessionFactory(DataSource dynamicDataSource) {
        MybatisSqlSessionFactoryBean sessionFactoryBean = new MybatisSqlSessionFactoryBean();
        sessionFactoryBean.setDataSource(dynamicDataSource);
        sessionFactoryBean.setConfigLocation(new ClassPathResource("/mybatis/mybatis-config.xml"));
        sessionFactoryBean.setMapperLocations(ResourceUtil.getPathMatchingResource(mapperLocations));
        sessionFactoryBean.setTransactionFactory(new MultiDataSourceTransactionFactory());
        return sessionFactoryBean;
    }

}
